package com.stupidzhe.vbreview.interceptor;

import com.stupidzhe.vbreview.cache.StudentCache;
import com.stupidzhe.vbreview.domain.Student;
import com.stupidzhe.vbreview.util.CookieUtil;
import com.stupidzhe.vbreview.util.Md5Util;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class StuStatusInterceptor implements HandlerInterceptor {

    private final StudentCache studentCache;

    public StuStatusInterceptor(StudentCache studentCache) {
        this.studentCache = studentCache;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie cookie = CookieUtil.getCookieByName(request, "s_cookie");

        // 1.判断cookie是否存在
        if (cookie == null) {
            request.setAttribute("need_login", true);
            request.getRequestDispatcher("/stu/status/check").forward(request, response);
            return false;
        }

        // 2.判断cookie是否被篡改
        String[] cookieValue = cookie.getValue().split("[|]");
        String md5Val = Md5Util.getPwd(cookieValue[0] + Md5Util.salt);
        if (2 != cookieValue.length || !md5Val.equals(cookieValue[1])) {
            cookie = new Cookie("s_cookie", null);
            cookie.setMaxAge(0);
            response.addCookie(cookie);
            request.setAttribute("need_login", true);
            request.getRequestDispatcher("/stu/status/check").forward(request, response);
            return false;
        }

        // 3.判断会话是否过期
        Student student = studentCache.getStudent(cookieValue[0]);
        if (student == null) {
            cookie = new Cookie("s_cookie", null);
            cookie.setMaxAge(0);
            response.addCookie(cookie);
            request.setAttribute("need_login", true);
            request.getRequestDispatcher("/stu/status/check").forward(request, response);
            return false;
        }

        request.setAttribute("student", student);
        return true;
    }
}
